const userService = require('../services/userService');

const auth = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  if (!authHeader) return res.status(401).json({ message: '未登录' });
  const token = authHeader.split(' ')[1];
  if (!token) return res.status(401).json({ message: '未登录' });
  const user = userService.verifyToken(token);
  if (!user) return res.status(401).json({ message: '无效token' });
  req.user = user;
  next();
};

const roleAuth = (roles) => (req, res, next) => {
  if (!req.user) return res.status(401).json({ message: '未登录' });
  if (!roles.includes(req.user.role)) return res.status(403).json({ message: '无权限' });
  next();
};

module.exports = auth;
module.exports.roleAuth = roleAuth; 